import { type ImportAppMeta } from "@cdyun/types"
import { fileURLToPath } from "url"
import { type UserConfig, loadEnv } from "vite"
import { setupViteBuild } from "./build"
import { setupViteServer } from "./server"
import { setupVitePlugins } from "./plugins"

export async function createViteConfig(
	command: 'build' | 'serve',
	mode: string,
	rootPath: string
): Promise<UserConfig> {
	const env = loadEnv(mode, rootPath) as unknown as ImportAppMeta
	const commonConfig: UserConfig = {
		plugins: await setupVitePlugins(env, rootPath, command === "build"),
		root: rootPath,
		base: env.VITE_APP_URL,
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url))
			}
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@use "@/assets/css/element/index.scss" as *;`
				}
			}
		},
		server: setupViteServer(env),
		build: setupViteBuild(rootPath),
		define: {
			__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
			__APP_NAME__: JSON.stringify('vue-admin')
		}
	}

	return commonConfig
}